import {CallStatistic} from '../sys_mng/statistic/callModule.jsx'
class DashBoard extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            /* common */
            commCount : 0,
            unitCount : '--',
            roomCount : '--',
            ownerCount : '--',
            rentCount : '--',
            managerStaffCount : '--',
            parks : '--',
            parkLots : '--',

            /* 物业角色 */
            ownerApplyingCount : '--',
            parkLotsUsedPercent : '--',
            devCount : '--',
            devOnlinePercent: '0',
            cardCount : '--',
            cardExpire : '--',
            repairPending : '--',
            propertyRerearage : '--',

            /* admin */
            feedback : '0',
            aliPay : '0'
        }

        this.ownerTypeMap = {
            "0" : "owner",
            "1" : "ownerApplying",
            "3" : "managerStaff",
            "5" : "rented"
        }

        this.initialized = false;
    }

    getOwnerCountFromArrData(name,data){
        for(let i =0; i < data.length; i++){
            if(name === this.ownerTypeMap[data[i].applyType])
                return data[i].count;
        }

        return "0";
    }

    parkDataHandler(data){
        let parkInfo = data.data.park?data.data.park:{};
        let parks = 0;
        let parkLots = 0;
        let parkEntered = 0;
        for(let key in parkInfo){
            parks++;
            let parkArr = parkInfo[key].split("-");
            if(parkArr && parkArr.length == 2){
                parkLots += parseInt(parkArr[0]);
                parkEntered += parseInt(parkArr[1]);
            }
        }

        let parkLotsPercent = Math.round(parkLots?parkEntered *100 / parkLots:parkLots);

        return {
            parks : parks,
            parkLots : parkLots,
            parkLotsPercent : parkLotsPercent
        }
    }

    devsHandler(data){
        let devs = data.data.devs?data.data.devs:[];

        let devCount = 0;
        let devOffline = 0;
        for(let i=0; i < devs.length; i++){
            for(let key in devs[i]){
                devCount++;
                devOffline += parseInt(devs[i][key].substr(devs[i][key].length - 1));
            }

        }

        return {
            devCount : devCount,
            devOnlinePercent :  Math.round(devCount?(devCount - devOffline)*100/devCount:devCount)
        }
    }

    cardHandler(data){
        let cardCount = 0;
        let cardExpire = 0;
        let cardData = data.data.card?data.data.card:[];

        for(let i=0; i<cardData.length; i++){
            if(cardData[i].state == 'E')
                cardExpire = cardData[i].count;

            cardCount += cardData[i].count;
        }

        return {
            count : cardCount,
            expire : cardExpire
        }
    }

    getDashBoardInfos(){
        let time = (new Date()).getTime();
        postJson("/LoginCtrl/getDashBoardInfo.x", null, (data) => {
            console.log(data);
            time = (new Date()).getTime() - time;
            console.log("cost "+time);
            let units = data.data.units;
            let owners = data.data.owners;

            let rooms = 0;
            for(let i=0; i < units.length; i++){
                let floor = units[i];
                rooms += floor[0]*floor[1];
            }

            let parkData = this.parkDataHandler(data);
            let devData = this.devsHandler(data);
            let cardData = this.cardHandler(data);
            let repairPending = data.data.repair;
            let propertyArrearage = data.data.propertyArrearage;
            this.initialized = true;

            this.setState({
                /* common */
                unitCount : units.length,
                roomCount : rooms,
                ownerCount: this.getOwnerCountFromArrData("owner",owners),
                ownerApplyingCount : this.getOwnerCountFromArrData("ownerApplying",owners),
                managerStaffCount : this.getOwnerCountFromArrData("managerStaff",owners),
                rentCount : this.getOwnerCountFromArrData("rented",owners),
                parks : parkData.parks,
                parkLots : parkData.parkLots,

                /* 物业角色 */
                parkLotsUsedPercent: parkData.parkLotsPercent,
                devCount : devData.devCount,
                devOnlinePercent : devData.devOnlinePercent,
                cardCount : cardData.count,
                cardExpire: cardData.expire,
                repairPending: repairPending,
                propertyRerearage: propertyArrearage,

                /* admin角色 */
                feedback : data.data.feedback?data.data.feedback:'0',
                aliPay : data.data.aliPay?data.data.aliPay:'0'
            })
        })
    }

    componentDidMount(){
        /* dashboard加载太快时，有可能权限表还没有加载到前端 */

        if (securityReady()) {
            if(!hasPerms("forbidenDashboard"))
                this.getDashBoardInfos();
        } else {
            getRolesAndPermissions(
                () => {
                    if(!hasPerms("forbidenDashboard"))
                        this.getDashBoardInfos();
                }
            )
        }

    }

    commOnChange(comm){
        if(this.refs.callStatistic)
            this.refs.callStatistic.init(comm);

        this.setState({commCount : this.refs.commSelect.commCount});
    }

    render(){
        /* 有些私有部署平台可能缺少一些功能，防止报错和无用显示,干脆提供开关禁止dashbaord */
        if(!this.initialized || hasPerms("forbidenDashboard"))
            return ('');
        else
            return(
                    <Row space="15">
                        <Col md="8">
                            <Row space="15">
                                <Col md="6">
                                    <Card header="楼宇信息">
                                        <Row>
                                            <Col xs="4">
                                                <InfoItem title="小区" value={this.state.commCount} icon="bank"/>
                                            </Col>

                                            <Col xs="4">
                                                <InfoItem title="单元" value={this.state.unitCount} icon="building"/>
                                            </Col>

                                            <Col xs="4">
                                                <InfoItem title="户数" value={this.state.roomCount} icon="home"/>
                                            </Col>
                                        </Row>
                                    </Card>
                                </Col>
                                <Col md="6">
                                    <Card header="人员信息">
                                        <Row>
                                            <Col xs="4">
                                                <InfoItem title="业主数量" value={this.state.ownerCount} icon="user"/>
                                            </Col>

                                            <Col xs="4">
                                                <InfoItem title="租客数量" value={this.state.rentCount} icon="user"/>
                                            </Col>

                                            <Col xs="4">
                                                <InfoItem title="员工数量" value={this.state.managerStaffCount} icon="user"/>
                                            </Col>
                                        </Row>
                                    </Card>
                                </Col>
                                <Col md="6">
                                    <Card header="停车场信息">
                                        <Row>
                                            <Col xs="6">
                                                <InfoItem title="停车场数量" value={this.state.parks} icon="car"/>
                                            </Col>

                                            <Col xs="6">
                                                <InfoItem title="车位总数" value={this.state.parkLots} icon="product-hunt"/>
                                            </Col>
                                            <br/>
                                            <SecurityCheck roles="secLevel | property">
                                                <Col xs="12">
                                                    <ProgressBar percent={this.state.parkLotsUsedPercent+"%"} title="车位使用比率" color="green"/>
                                                </Col>
                                            </SecurityCheck>
                                        </Row>
                                    </Card>
                                </Col>
                                <Col md="6">
                                    <Card header="门禁信息">
                                        <Row>
                                            <Col xs="4">
                                                <InfoItem title="设备总数" value={this.state.devCount} icon="building-o"/>
                                            </Col>

                                            <Col xs="4">
                                                <InfoItem title="已发IC卡" value={this.state.cardCount} icon="credit-card"/>
                                            </Col>

                                            <Col xs="4">
                                                <InfoItem title="IC卡到期" value={this.state.cardExpire} icon="credit-card-alt" color="red"/>
                                            </Col>
                                            <br/>
                                            <SecurityCheck roles="secLevel | property">
                                                <Col xs="12">
                                                    <ProgressBar percent={this.state.devOnlinePercent+"%"} title="设备在线比率"/>
                                                </Col>
                                            </SecurityCheck>
                                        </Row>
                                    </Card>
                                </Col>
                                <Col md="12">
                                    <LayuiCommSelect mask={['building', 'unit', 'floor', 'room']} firstValue={hasRoles("admin")?"公司总部":""}
                                                     onChangeComm={(comm) => this.commOnChange(comm)} style={{display:"none"}} ref="commSelect"/>
                                    <SecurityCheck roles="admin | property" perms="hasAliLog">
                                        <Card header="数据统计">
                                            <CallStatistic ref="callStatistic"/>
                                        </Card>
                                    </SecurityCheck>
                                </Col>
                            </Row>
                        </Col>
                        <Col md="4">
                            <Card header="待办事项">
                                <Row>
                                    <SecurityCheck roles="secLevel | property">
                                        <Col md={hasPerms("property:pay")?"4":"6"}>
                                            <BackLog title="业主申请" value={this.state.ownerApplyingCount}
                                                     link="/pages/business/owner/query.html?applyType=applying"/>
                                        </Col>
                                        <Col md={hasPerms("property:pay")?"4":"6"}>
                                            <BackLog title="新的报修" value={this.state.repairPending}
                                                     link="/pages/business/repair/query.html"/>
                                        </Col>
                                        <SecurityCheck perms="property:pay">
                                        <Col md="4">
                                            <BackLog title="物业欠费" value={this.state.propertyRerearage}
                                                     link="/pages/business/property/fee/PropertyFee.html"/>
                                        </Col>
                                        </SecurityCheck>
                                    </SecurityCheck>
                                    <SecurityCheck roles="admin">
                                        <Col md="6">
                                            <BackLog title="客户反馈" value={this.state.feedback}
                                                     link="/pages/business/feedback/query.html"/>
                                        </Col>
                                        <Col md="6">
                                            <BackLog title="代签商户" value={this.state.aliPay}
                                                     link="/pages/business/customer/payCustAliApplying.html"/>
                                        </Col>
                                    </SecurityCheck>
                                </Row>
                            </Card>
                        </Col>
                    </Row>
                )

    }

}

ReactDOM.render(<DashBoard/>,document.getElementById("dashboard"));